package com.xmjs.baselibrary.view.animview.number;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.Nullable;

import com.xmjs.baselibrary.R;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 带随机动画的数值控件
 * 特点：1.每位数字随机变化直到指定的数字；2.保留2位小数
 */
public class RandomNumber extends View implements Animator.AnimatorListener{
    Paint paint = new Paint();

    //动画持续时间
    private long duration = 700;
    //上移到增量
    private float position;
    //小数点所在位置
    private int index;
    //字体大小
    private float textSize = 40;
    //数目
    private double number;
    //字体颜色
    private int textColor = Color.BLACK;

    List<String> numbers = new ArrayList<>();

    public RandomNumber(Context context) {
        this(context, null);
    }

    public RandomNumber(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RandomNumber(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.AnimView);
        textSize = (int) ta.getDimension(R.styleable.AnimView_TextSize, 40);
        textColor = (int) ta.getColor(R.styleable.AnimView_TextColor, Color.BLACK);
        ta.recycle();

        paint.setTextSize(textSize);
        paint.setColor(textColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
        setMeasuredDimension(width + getTextWidth() * 2, height + getTextHeight() / 6);
    }

    /**
     * 根据xml的设定获取宽度
     *
     * @param measureSpec
     * @return
     */
    private int measureWidth(int measureSpec) {
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.AT_MOST) { //wrap_content
            specSize = width();
        } else if (specMode == MeasureSpec.EXACTLY) {//fill_parent或者精确值
            specSize = width();
        }
        return specSize;

    }

    /**
     * 根据xml的设定获取高度
     *
     * @param measureSpec
     * @return
     */
    private int measureHeight(int measureSpec) {
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if (specMode == MeasureSpec.AT_MOST) {//wrap_content
            specSize = getTextHeight();
        } else if (specMode == MeasureSpec.EXACTLY) {//fill_parent或者精确值
            specSize = getTextHeight();
        }
        return specSize;
    }

    public float getPosition() {
        return position;
    }

    public void setPosition(float position) {
        this.position = position;
        invalidate();
    }

    public void setNumber(double number) {
        setMinimumWidth(width() + 10);
        this.number = number;
        numbers.clear();
        char[] nums = format(number).toCharArray();
        for (int i = 0; i < nums.length; i++) {
            numbers.add(nums[i] + "");
        }
        startAnimation();
    }

    public double getNumber() {
        return number;
    }

    /**
     * 保留2位小数
     *
     * @param number
     * @return
     */
    public String format(double number) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(number);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            //数字为0时不执行随机数动画
            if (number == 0) {
                for (int i = 0; i < numbers.size(); i++) {
                    if (!numbers.get(i).equals(".")) {//绘制0
                        if (i < index)
                            canvas.drawText(0 + "", i * getTextWidth() * 1.2f, getTextHeight(), paint);
                        else
                            canvas.drawText(0 + "", i * getTextWidth() * 1.2f - getTextWidth() * 2 / 3, getTextHeight(), paint);
                    } else {//绘制小数点
                        index = i;
                        canvas.drawText(".", i * getTextWidth() * 1.2f, getTextHeight(), paint);
                    }
                }
                return;
            }

            //停止下来时绘制数字
            if (position >= 10) {
                for (int i = 0; i < numbers.size(); i++) {
                    if (!numbers.get(i).equals(".")) {//绘制随机数字
                        if (i < index)
                            canvas.drawText(numbers.get(i) + "", i * getTextWidth() * 1.2f, getTextHeight(), paint);
                        else
                            canvas.drawText(numbers.get(i) + "", i * getTextWidth() * 1.2f - getTextWidth() * 2 / 3, getTextHeight(), paint);
                    } else {//绘制小数点
                        index = i;
                        canvas.drawText(".", i * getTextWidth() * 1.2f, getTextHeight(), paint);
                    }

                }

            } else {
                for (int i = 0; i < numbers.size(); i++) {
                    if (!numbers.get(i).equals(".")) {//绘制随机数字
                        if (i < index)
                            canvas.drawText(getRandom() + "", i * getTextWidth() * 1.2f, getTextHeight(), paint);
                        else
                            canvas.drawText(getRandom() + "", i * getTextWidth() * 1.2f - getTextWidth() * 2 / 3, getTextHeight(), paint);
                    } else {//绘制小数点
                        index = i;
                        canvas.drawText(".", i * getTextWidth() * 1.2f, getTextHeight(), paint);
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取字体颜色
     *
     * @return
     */
    public int getTextColor() {
        return textColor;
    }

    /**
     * 设置字体颜色
     *
     * @param textColor
     */
    public void setTextColor(int textColor) {
        this.textColor = textColor;
        paint.setColor(textColor);
        invalidate();
    }

    /**
     * 获取随机数
     *
     * @return
     */
    private int getRandom() {
        return new Random().nextInt(9);
    }

    /**
     * 获取单个数字的宽度
     *
     * @return
     */
    private int getTextWidth() {
        Rect rect = new Rect();
        paint.setTextSize(textSize);
        paint.getTextBounds("9", 0, "9".length(), rect);
        return rect.width();
    }

    /**
     * 获取单个数字的高度
     *
     * @return
     */
    private int getTextHeight() {
        Rect rect = new Rect();
        paint.setTextSize(textSize);
        paint.getTextBounds("9", 0, "9".length(), rect);
        return rect.height();
    }

    /**
     * 整个数值的宽度
     *
     * @return
     */
    private int width() {
        Rect rect = new Rect();
        paint.setTextSize(textSize);
        paint.getTextBounds(number + "", 0, (number + "").length(), rect);
        return rect.width();
    }

    /**
     * 开始执行动画
     */
    private void startAnimation() {
        setLayerType(LAYER_TYPE_HARDWARE, null);
        ObjectAnimator an = ObjectAnimator.ofFloat(this, "position", 0, 10);
        an.setInterpolator(new DecelerateInterpolator());
        an.setDuration(duration);
        an.start();
    }

    @Override
    public void onAnimationStart(Animator animator) {

    }

    @Override
    public void onAnimationEnd(Animator animator) {
        setLayerType(LAYER_TYPE_NONE, null);
    }

    @Override
    public void onAnimationCancel(Animator animator) {

    }

    @Override
    public void onAnimationRepeat(Animator animator) {

    }
}
